<template>
  <div
    style="
      display: flex;
      margin-bottom: 5px;
      height: 70px;
      width: 100vw;
      justify-content: space-between;
    "
  >
    <div
      class="left"
      style="margin-left: 10px; display: flex; align-items: center"
    >
      <span style="font-size: 45px; color: black; font-weight: bold">
        VICHI.
      </span>
      <el-menu
        mode="horizontal"
        :router="true"
        :active-text-color="activeTextColor"
        :text-color="textColor"
        background-color="transparent"
        class="nav-menu"
        style="padding: 10px"
        :ellipsis="false"
      >
        <el-menu-item index="/home">
          <GlowingEffect
            :spread="40"
            :glow="true"
            :disabled="false"
            :proximity="64"
            :inactive-zone="0.01"
          />
          首页
        </el-menu-item>
        <el-menu-item index="/companionship">
          <GlowingEffect
            :spread="40"
            :glow="true"
            :disabled="false"
            :proximity="64"
            :inactive-zone="0.01"
          />
          智伴优学
        </el-menu-item>
        <el-menu-item index="/ask">
          <GlowingEffect
            :spread="40"
            :glow="true"
            :disabled="false"
            :proximity="64"
            :inactive-zone="0.01"
          />
          睿记精解
        </el-menu-item>
        <el-menu-item index="/talk">
          <GlowingEffect
            :spread="40"
            :glow="true"
            :disabled="false"
            :proximity="64"
            :inactive-zone="0.01"
          />
          心聆秘语
        </el-menu-item>
        <el-menu-item index="/note">
          <GlowingEffect
            :spread="40"
            :glow="true"
            :disabled="false"
            :proximity="64"
            :inactive-zone="0.01"
          />
          笔记
        </el-menu-item>
      </el-menu>
    </div>
    <div class="right" style="display: flex; width: 20%">
      <div style="padding: 10px; margin-left: 60px">
        <el-avatar
          shape="square"
          size="default"
          :src="avatarUrl"
          style="border: 2px solid black; margin-top: 10px; cursor: pointer"
          @click="handleAvatarClick"
        />
      </div>
      <div style="margin-left: 10px; margin-top: 30px">
        <span
          style="font-weight: bold; font-size: 20px; cursor: pointer"
          :style="!isLogin ? 'color: #ff9800; text-decoration: underline;' : ''"
          @click="handleAvatarClick"
        >
          {{ username }}
        </span>
      </div>
    </div>
    <UserSidebar
      :show="showSidebar"
      @close="showSidebar = false"
      @logout="handleLogout"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import GlowingEffect from "@/components/ui/glowing-effect/GlowingEffect.vue";
import UserSidebar from "@/components/UserSidebar.vue";
import "@/assets/main.css";
import defaultAvatar from "@/assets/character.png";

const avatarUrl = ref(defaultAvatar);
const textColor = ref("#000000");
const activeTextColor = ref("#409EFF");
const router = useRouter();
const route = useRoute();
const showSidebar = ref(false);

// 从sessionStorage获取用户信息和token
const userInfo = ref(JSON.parse(sessionStorage.getItem("userInfo") || "{}"));
const token = ref(sessionStorage.getItem("token") || "");

// 监听sessionStorage变化（跨页面同步）
window.addEventListener("storage", (e) => {
  if (e.key === "token") {
    token.value = e.newValue || "";
  }
  if (e.key === "userInfo") {
    userInfo.value = JSON.parse(e.newValue || "{}");
  }
});

// 监听同页面内的sessionStorage变化
const originalSetItem = sessionStorage.setItem;
sessionStorage.setItem = function (key, value) {
  const event = new CustomEvent("sessionStorageChange", {
    detail: { key, newValue: value },
  });
  window.dispatchEvent(event);
  originalSetItem.apply(this, [key, value]);
};

window.addEventListener("sessionStorageChange", (e) => {
  if (e.detail.key === "token") {
    token.value = e.detail.newValue || "";
  }
  if (e.detail.key === "userInfo") {
    userInfo.value = JSON.parse(e.detail.newValue || "{}");
  }
});

// 响应式计算用户名
const username = computed(() => {
  console.log("TopNavBar - 计算用户名:", {
    token: token.value,
    userInfo: userInfo.value,
    username: userInfo.value?.username || userInfo.value?.name,
  });

  if (
    token.value &&
    userInfo.value &&
    (userInfo.value.username || userInfo.value.name)
  ) {
    return userInfo.value.username || userInfo.value.name;
  }
  return "请登录";
});

// 响应式计算登录状态
const isLogin = computed(() => {
  const loginStatus = !!(
    token.value &&
    userInfo.value &&
    (userInfo.value.username || userInfo.value.name)
  );
  console.log("TopNavBar - 登录状态:", loginStatus);
  return loginStatus;
});

// 初始化时获取用户信息
onMounted(() => {
  const storedToken = sessionStorage.getItem("token");
  const storedUserInfo = sessionStorage.getItem("userInfo");

  console.log("TopNavBar - 初始化:", {
    storedToken,
    storedUserInfo,
    parsedUserInfo: storedUserInfo ? JSON.parse(storedUserInfo) : null,
  });

  if (storedToken) {
    token.value = storedToken;
  }
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo);
  }
});

// 监听token变化，自动刷新用户信息
watch(token, (newToken) => {
  if (newToken) {
    // 如果有token但没有用户信息，尝试重新获取
    const storedUserInfo = sessionStorage.getItem("userInfo");
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo);
    }
  } else {
    // 如果没有token，清除用户信息
    userInfo.value = {};
  }
});

function handleAvatarClick() {
  console.log("TopNavBar - 点击头像:", { isLogin: isLogin.value });
  if (isLogin.value) {
    // 已登录时打开侧边栏
    showSidebar.value = true;
  } else {
    // 未登录时跳转到登录页
    router.push("/login");
  }
}

function handleNameClick() {
  console.log("TopNavBar - 点击用户名:", { isLogin: isLogin.value });
  if (isLogin.value) {
    // 已登录时跳转到个人中心
    router.push("/userCenter");
  } else {
    // 未登录时跳转到登录页
    router.push("/login");
  }
}

function handleLogout() {
  console.log("TopNavBar - 处理登出");
  // 清除所有sessionStorage数据
  sessionStorage.removeItem("token");
  sessionStorage.removeItem("userInfo");
  sessionStorage.removeItem("menuList");

  // 重置本地状态
  token.value = "";
  userInfo.value = {};
  showSidebar.value = false;

  // 跳转到登录页
  router.push("/login");
}
</script>

<style scoped>
.nav-menu {
  border: none;
}

.el-menu-item:hover {
  background-color: transparent !important;
}

.el-menu-item {
  margin: 0 3px 0 3px;
  font-size: 18px;
}
</style>
